package box

import (
	"github.com/Amovement/password-box/pkg/config"
	"github.com/Amovement/password-box/pkg/models"
	BoxServer "github.com/Amovement/password-box/pkg/server/box_server"
	"github.com/Amovement/password-box/pkg/utils/result"
	"github.com/gin-gonic/gin"
)

type BoxRegister struct {
}

func (s *BoxRegister) DeleteBox(c *gin.Context) {
	result := result.NewResult(c)

	var box_token *models.BoxWithToken
	err := c.BindJSON(&box_token)
	if err != nil {
		result.Error(500, "Box Data Loss")
		return
	}
	cfg := config.GetConfig()
	if box_token.Token != cfg.App.Boxtoken {
		result.Error(500, "Box Token Error")
		return
	}

	err = BoxServer.DeleteBox(&box_token.Box)
	if err != nil {
		result.DefaultError()
		return
	}
	result.Success(nil)
}

func (s *BoxRegister) CreateBox(c *gin.Context) {
	result := result.NewResult(c)

	var box_token *models.BoxWithToken
	err := c.BindJSON(&box_token)
	if err != nil {
		result.Error(500, "Box Data Loss")
		return
	}
	cfg := config.GetConfig()
	if box_token.Token != cfg.App.Boxtoken {
		result.Error(500, "Box Token Error")
		return
	}

	box, err := BoxServer.CreateBox(&box_token.Box)
	if err != nil {
		result.DefaultError()
		return
	}
	result.Success(box)
}

func (s *BoxRegister) ListBox(c *gin.Context) {
	result := result.NewResult(c)

	var user *models.User
	err := c.BindJSON(&user)
	if err != nil {
		result.Error(500, "Data Loss")
		return
	}

	boxs, err := BoxServer.ListBoxByUsername(user.Username)
	if err != nil {
		result.DefaultError()
		return
	}
	result.Success(boxs)
}

func (s *BoxRegister) GetBox(c *gin.Context) {
	result := result.NewResult(c)

	var box *models.Box
	err := c.BindJSON(&box)
	if err != nil {
		result.Error(500, "Data Loss")
		return
	}

	box, err = BoxServer.GetBoxById(box.ID)
	if err != nil {
		result.DefaultError()
		return
	}
	result.Success(box)
}
